package com.schoolcloud.gateway.config;

import com.alibaba.fastjson2.JSON;
import com.schoolcloud.common.exception.UserNotExistException;
import com.schoolcloud.common.model.R;
import com.schoolcloud.common.model.REnum;
import org.springframework.boot.web.reactive.error.ErrorWebExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.core.annotation.Order;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebExceptionHandler;
import reactor.core.publisher.Mono;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.util.Map;

@Component
@Order(-1)
public class GatewayExceptionHandler implements ErrorWebExceptionHandler {

    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
//        此异常处理只能处理网关抛出的异常（例如访问不存在的路径，网关无法匹配的路由）
        try {
            HttpStatusCode httpStatusCode = HttpStatusCode.valueOf(200);
            String requestPath = exchange.getRequest().getPath().value();
            System.out.println("网关异常处理 - 请求路径: " + requestPath);
            R<Object> err = R.err(REnum.NOT_FOUND);
            byte[] bytes = null;
            //            序列化为字节流
            bytes = objectMapper.writeValueAsBytes((err));
            exchange.getResponse().setStatusCode(httpStatusCode);
            exchange.getResponse().getHeaders().setContentType(MediaType.APPLICATION_JSON);
            return exchange.getResponse().writeWith(Mono.just(exchange.getResponse().bufferFactory().wrap(bytes)));
        } catch (Exception e) {
            return Mono.error(e);
        }
    }
}
